package wanba.wanbatv.com.wudao.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

import cn.ffcs.itvpay.ItvPayTask;
import wanba.wanbatv.com.wudao.R;
import wanba.wanbatv.com.wudao.util.AppUtil;
import wanba.wanbatv.com.wudao.util.Crypto;
import wanba.wanbatv.com.wudao.util.Util;
import wanba.wanbatv.com.wudao.utils.Product;


public class OpenwudaoActivityAction implements View.OnClickListener {
	@SuppressWarnings("rawtypes")
	private Class activityClass;
	private Map<String, String> params;
	private Context context;

	private String mProductCode = null;
	private String mTranId = null;
	private boolean mNeedAuth = false;
	private Drawable mOrderPrimaryButtonBackground = null;
	private Drawable mOrderSecondaryButtonBackground = null;

	private View.OnClickListener mListener = null;
	private AlertDialog myDialog=null;

	JSONArray arr_zhifubao=null;
	String orderInfo=null;
	public OpenwudaoActivityAction(Context context, Class activityClass,
								   Map<String, String> params) {
		this.activityClass = activityClass;
		this.context = context;
		this.params = params;
	}

	public OpenwudaoActivityAction(Context context, Class activityClass) {
		this.activityClass = activityClass;
		this.context = context;
	}

	public OpenwudaoActivityAction setOrderPrimaryButtonBackground(Drawable drawable) {
		mOrderPrimaryButtonBackground = drawable;
		return this;
	}

	public Drawable getOrderPrimaryButtonBackground() {
		return mOrderPrimaryButtonBackground;
	}

	public OpenwudaoActivityAction setOrderSecondaryButtonBackground(Drawable drawable) {
		mOrderSecondaryButtonBackground = drawable;
		return this;
	}

	public Drawable getOrderSecondaryButtonBackground() {
		return mOrderSecondaryButtonBackground;
	}

	public OpenwudaoActivityAction setNeedAuth(boolean needAuth) {
		mNeedAuth = needAuth;
		return this;
	}

	public boolean isNeedAuth() {
		return mNeedAuth;
	}

	public OpenwudaoActivityAction setProductCode(String productCode) {
		mProductCode = productCode;
		return this;
	}

	public String getProductCode() {
		return mProductCode;
	}

	public OpenwudaoActivityAction setTranId(String tranId) {
		mTranId = tranId;
		return this;
	}

	public String getTranId() {
		return mTranId;
	}

	@Override
	public void onClick(final View v) {
		if (mListener != null) {
			mListener.onClick(v);
		}

//		if (true) {
//			Intent intent = new Intent(context, activityClass);
//
//			if (params != null) {
//				for (String str : params.keySet()) {
//					intent.putExtra(str, params.get(str));
//				}
//			}
//			context.startActivity(intent);
//			return;
//		}

		if (LoginWudaoActivity.is_dinggou) {
			Intent intent = new Intent(context, activityClass);

			if (params != null) {
				for (String str : params.keySet()) {
					intent.putExtra(str, params.get(str));
				}
			}
			context.startActivity(intent);
		} else {
//			Intent it=new Intent();
//			it.setClass(context,PayWudaoActivity.class);
//			context.startActivity(it);
			creatAlertDialog_tuichu();
		}

	}

	public OpenwudaoActivityAction setOnClickListener(View.OnClickListener l) {
		mListener = l;
		return this;
	}
	private void creatAlertDialog_tuichu() {

		myDialog = new AlertDialog.Builder(context).create();

		myDialog.show();

		myDialog.getWindow().setContentView(R.layout.diolag_queding);

		myDialog.getWindow()
				.findViewById(R.id.no_iv)
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						myDialog.dismiss();

					}

				});
		myDialog.getWindow()
				.findViewById(R.id.yes_iv)
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						myDialog.dismiss();
//			Intent it=new Intent();
//			it.setClass(context,PayWudaoActivity.class);
//			context.startActivity(it);
						chanpinbao();

					}

				});
	}
	private void chanpinbao(){
		RequestQueue rq_2 = Volley.newRequestQueue(context.getApplicationContext());

		final JsonObjectRequest request_2 = new JsonObjectRequest("http://121.201.7.173:8063/proxy/61.191.46.214/8087/getapi/common/subjects/31259d2c48bec6a1ba589360c748e132?flavor="+ Product.flavor, null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject jsonObject) {
						try {
							JSONObject obj=jsonObject.getJSONObject("data");
							JSONArray arr=obj.getJSONArray("list");
							arr_zhifubao=arr;
							dingdanhao();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError volleyError) {
				Toast.makeText(context,"请求产品包超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

			}
		}

		) {
			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				HashMap<String, String> headers = new HashMap<String, String>();
				PackageInfo pi= null;
				try {
					pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
					headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
					headers.put("app_version", pi.versionName);
					headers.put("app_package_name",pi.packageName);
				} catch (PackageManager.NameNotFoundException e) {
					e.printStackTrace();
				}


				// MyLog.d(TAG, "headers=" + headers);
				return headers;
			}
		};
		request_2.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));

		rq_2.add(request_2);
	}
	private  void dingdanhao(){

		try {
			JSONObject obj = arr_zhifubao.getJSONObject(0);

			final   String subject=obj.getString("subject");
			final   String subjectid=obj.getString("subjectId");
			final   String price=obj.getString("price");
			RequestQueue requestQueue = Volley.newRequestQueue(context);
			String url="http://121.201.7.173:8063/proxy/61.191.46.214/8087/postapi/common/wpay/getorder";
			StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
					new Response.Listener<String>() {
						@Override
						public void onResponse(String response) {
							JSONObject obj_zhifubao= null;
							try {

								obj_zhifubao = (JSONObject) new JSONTokener(response).nextValue();

								JSONObject oobj=obj_zhifubao.getJSONObject("data");
								String order=oobj.getString("order");
								orderInfo="orderId="+order+"|itvAccount="+ AppUtil.STB.UserID+"|productId=zg_wanba"+"|price=1500";
								orderInfo=jiami(orderInfo);
								Log.e("anhui", "get subject "+obj_zhifubao);
								ItvPayTask itvPayTask = new ItvPayTask((Activity) context);
								HashMap<String, String> data = new HashMap<String, String>();
								data.put(ItvPayTask.NET_IP, "61.191.45.118");//访问地址ip 测试ip为61.191.45.116 正式为//61.191.45.118
								data.put(ItvPayTask.NET_PORT, "7002");//访问地址端口
								data.put(ItvPayTask.DEVICEMODEL, AppUtil.STB.Model);//机顶盒信息
//								data.put(ItvPayTask.RETURNURL, "http://61.191.46.214:8087/getapi/common/wpay/result/ahpay/");//同步返回地址
								data.put(ItvPayTask.NOTIFYURL, "http://172.16.33.228:8087/postapi/common/wpay/paynotify/ahpay/");//异步通知地址
								data.put(ItvPayTask.DEVICETYPE, "hd");//机顶盒信息
								data.put(ItvPayTask.USERAGENT, "wanba");//机顶盒信息
								data.put(ItvPayTask.DEVICESERIALNO, AppUtil.STB.Sn);//机顶盒信息
								data.put(ItvPayTask.IP, AppUtil.STB.IP);//机顶盒信息
								data.put(ItvPayTask.ORDERINFO, orderInfo);//订单信息
								data.put(ItvPayTask.PROVIDERID, "shzg");//供应商id
								itvPayTask.pay(data);

							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					}, new Response.ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError error) {
					Toast.makeText(context,"请求订单号超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

					error.printStackTrace();
				}
			}) {
				@Override
				public Map<String, String> getHeaders() throws AuthFailureError {
					HashMap<String, String> headers = new HashMap<String, String>();
					PackageInfo pi= null;
					try {
						pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
						headers.put("accept", "applicationnd.com.wanbatv.wanba.jianshencao;version="+pi.versionName);
						headers.put("app_version", pi.versionName);
						headers.put("app_package_name",pi.packageName);
					} catch (PackageManager.NameNotFoundException e) {
						e.printStackTrace();
					}


					// MyLog.d(TAG, "headers=" + headers);
					return headers;
				}
				@Override
				public String getBodyContentType() {
					return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
				}
				@Override
				protected Map<String, String> getParams() {
					//在这里设置需要post的参数
					HashMap<String, String> params = new HashMap<String, String>();
					params.put("partner","");
					params.put("subject", subject);
					params.put("subjectid",subjectid);
					params.put("price",price);
					params.put("provider","ahpay");
					params.put("stb", Util.getDeviceId(context));
					params.put("flavor", Product.flavor);

					return params;
				}
			};
			stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
			requestQueue.add(stringRequest);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	private  String jiami(String orderInfo){
//        String msg = "使用3DES对数据进行加密";
//        byte[] secretArr = DES3Utils.encryptMode(msg.getBytes());
//        String jiami=Base64.encodeToString(secretArr,Base64.DEFAULT);
//        String res = null;
//        try {
//            res = new String(DES3Utils.decryptMode(Base64.decode(jiami, Base64.DEFAULT)), "utf-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Log.e("jiami","3des result " + msg.equals(res) + " res " + res + ", encrypt " + jiami);

		String jiami= Crypto.TripleDES.encrypt(orderInfo,"26f545c0d092463185acdd3e2c73fdda");
//        String jiami=Crypto.TripleDES.decrypt(jiami,"36161889369a412b923af17dafb0fe88");
		Log.e("jiami",jiami);
//        Log.e("jiemi",jiemi);
		return jiami;
	}
}
